package com.kx.center.service.impl.mt;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kx.center.entity.Channel;
import com.kx.center.entity.mt.MtTrade;
import com.kx.center.entity.mt.MtTradeDetail;
import com.kx.center.mappers.ChannelMapper;
import com.kx.center.mappers.mt.MtTradeDetailMapper;
import com.kx.center.mappers.mt.MtTradeMapper;
import com.kx.center.service.mt.MtTradeService;
import com.kx.center.util.HttpClientUtil;
import com.kx.center.util.JSONParser;
import com.kx.center.util.MeiTuanUtil;

@Service
public class MtTradeServiceImpl implements MtTradeService {

	@Autowired
	MtTradeMapper mtTradeMapper;
	@Autowired
	MtTradeDetailMapper mtTradeDetailMapper;
	@Autowired
	ChannelMapper channelMapper;

	@Override
	public void insertMtTrade(MtTrade mtTrade) {
		mtTradeMapper.insertMtTrade(mtTrade);
	}

	@Override
	public void updateMtTradeStatus(MtTrade mtTrade) {
		mtTradeMapper.updateMtTradeStatus(mtTrade);
	}
	
	@Override 
	@SuppressWarnings("unchecked")
	public Integer saveMtTrade(HashMap<String, Object> data) {
		
		Integer mtStoreId = null;
		
		try {
			MtTrade mtTrade = new MtTrade();
			mtTrade.setOrderId(NumberUtils.toInt(data.get("order_id")
					.toString().trim()));
			mtTrade.setWmOrderIdView(data.get("wm_order_id_view").toString()
					.trim());
			mtTrade.setAppPoiCode(NumberUtils.toInt(data.get("app_poi_code")
					.toString().trim()));
			mtStoreId = mtTrade.getAppPoiCode();
			mtTrade.setWmPoiName(data.get("wm_poi_name").toString().trim());
			mtTrade.setWmPoiAddress(data.get("wm_poi_address").toString()
					.trim());
			mtTrade.setWmPoiPhone(NumberUtils.toInt(data.get("wm_poi_phone")
					.toString().trim()));
			mtTrade.setRecipientAddress(data.get("recipient_address")
					.toString().trim());
			mtTrade.setRecipientName(data.get("recipient_name").toString()
					.trim());
			mtTrade.setRecipientPhone(NumberUtils.toInt(data
					.get("recipient_phone").toString().trim()));
			mtTrade.setShippingFee(NumberUtils.toDouble(data
					.get("shipping_fee").toString().trim()));
			mtTrade.setTotal(NumberUtils.toDouble(data.get("total").toString()
					.trim()));
			mtTrade.setOriginalPrice(NumberUtils.toDouble(data
					.get("original_price").toString().trim()));
			mtTrade.setCaution(data.get("caution").toString().trim());
			mtTrade.setShipperPhone(NumberUtils.toInt(data.get("shipper_phone")
					.toString().trim()));
			mtTrade.setStatus(NumberUtils.toInt(data.get("status").toString()
					.trim()));
			mtTrade.setCityId(NumberUtils.toInt(data.get("city_id").toString()
					.trim()));
			mtTrade.setHasInvoiced(NumberUtils.toInt(data.get("has_invoiced")
					.toString().trim()));
			mtTrade.setInvoicedTitle(data.get("invoice_title").toString()
					.trim());
			mtTrade.setCtime(NumberUtils.toInt(data.get("ctime").toString()
					.trim()));
			mtTrade.setUtime(NumberUtils.toInt(data.get("utime").toString()
					.trim()));
			mtTrade.setDeliveryTime(NumberUtils.toInt(data.get("delivery_time")
					.toString().trim()));
			mtTrade.setIsThirdShipping(NumberUtils.toInt(data
					.get("is_third_shipping").toString().trim()));
			mtTrade.setPayType(NumberUtils.toInt(data.get("pay_type")
					.toString().trim()));
			mtTrade.setLatitude(data.get("latitude").toString().trim());
			mtTrade.setLongitude(data.get("longitude").toString().trim());
			mtTradeMapper.insertMtTrade(mtTrade);
			MtTradeDetail mtTradeDetail = new MtTradeDetail();
			ArrayList<HashMap<String, Object>> list = (ArrayList<HashMap<String, Object>>) JSONParser
					.parse((String) data.get("detail"),
							new ArrayList<HashMap<String, Object>>().getClass());
			for (HashMap<String, Object> detail : list) {
				mtTradeDetail.setOrderId(NumberUtils.toLong(data.get("order_id")
						.toString().trim()));
				mtTradeDetail.setAppPoiCode(NumberUtils.toInt(data
						.get("app_poi_code").toString().trim()));
				mtTradeDetail.setAppFoodCode(detail.get("app_food_code")
						.toString().trim());
				mtTradeDetail.setFoodName(detail.get("food_name").toString()
						.trim());
				mtTradeDetail.setSkuId(detail.get("sku_id").toString().trim());
				mtTradeDetail.setQuantity(NumberUtils.toInt(detail
						.get("quantity").toString().trim()));
				mtTradeDetail.setPrice(NumberUtils.toDouble(detail.get("price")
						.toString().trim()));
				mtTradeDetail.setBoxNum(NumberUtils.toInt(detail.get("box_num")
						.toString().trim()));
				mtTradeDetail.setBoxPrice(NumberUtils.toDouble(detail
						.get("box_price").toString().trim()));
				mtTradeDetail.setUnit(detail.get("unit").toString().trim());
				mtTradeDetail.setFoodDiscount(NumberUtils.toDouble(detail
						.get("food_discount").toString().trim()));
				mtTradeDetailMapper.insertMtTradeDetail(mtTradeDetail);
			}
		} catch (Exception e) {
			System.out.println(e);
		}
		return mtStoreId;
	}

	@Override
	@SuppressWarnings("unchecked")
	public String sendConfirmToMt(Long orderId) {

		Integer timestamp = (int) (System.currentTimeMillis() / 1000);
		String data = null;
		
		Channel channel = channelMapper.findKeyById(orderId);
		
		try {
			Map<String, String> map = new HashMap<String, String>();
			map.put("order_id", orderId.toString());
			String url = "http://test.waimaiopen.meituan.com/api/v1/order/confirm";
			String md5 = MeiTuanUtil.signRequest(url, map, channel.getAppKey(), channel.getAppSecret(),
					timestamp);
			map.put("app_id", channel.getAppKey());
			map.put("timestamp", timestamp.toString());
			map.put("sig", md5);
			String param = MeiTuanUtil.concatParams(map);
			String json = HttpClientUtil.sendGet(url, param);
			HashMap<String, Object> data_ = (HashMap<String, Object>) JSONParser
					.parse(json, new HashMap<String, Object>().getClass());
			data = (String) data_.get("data");
		} catch (Exception e) {
			System.out.println(e);
		}
		return data;
	}

	@Override
	@SuppressWarnings("unchecked")
	public String sendCancelToMt(Long orderId) {

		Integer timestamp = (int) (System.currentTimeMillis() / 1000);
		String data = null;
		
		Channel channel = channelMapper.findKeyById(orderId);
		
		try {
			Map<String, String> map = new HashMap<String, String>();
			map.put("order_id", orderId.toString());
			map.put("reason", "菜卖光了");
			map.put("reason_code", "1001");
			String url = "http://test.waimaiopen.meituan.com/api/v1/order/cancel";
			String md5 = MeiTuanUtil.signRequest(url, map, channel.getAppKey(), channel.getAppSecret(),
					timestamp);
			map.put("app_id", channel.getAppKey());
			map.put("timestamp", timestamp.toString());
			map.put("sig", md5);
			String param = MeiTuanUtil.concatParams(map);
			String json = HttpClientUtil.sendGet(url, param);
			HashMap<String, Object> data_ = (HashMap<String, Object>) JSONParser
					.parse(json, new HashMap<String, Object>().getClass());
			data = (String) data_.get("data");
		} catch (Exception e) {
			System.out.println(e);
		}
		return data;
	}

	@Override
	@SuppressWarnings("unchecked")
	public String sendDeliverToMt(Long orderId) {

		Integer timestamp = (int) (System.currentTimeMillis() / 1000);
		String data = null;
		
		Channel channel = channelMapper.findKeyById(orderId);
		
		try {
			Map<String, String> map = new HashMap<String, String>();
			map.put("order_id", orderId.toString());
			map.put("courier_name", "");
			map.put("courier_phone", "");
			String url = "http://test.waimaiopen.meituan.com/api/v1/order/delivering";
			String md5 = MeiTuanUtil.signRequest(url, map, channel.getAppKey(), channel.getAppSecret(),
					timestamp);
			map.put("app_id", channel.getAppKey());
			map.put("timestamp", timestamp.toString());
			map.put("sig", md5);
			String param = MeiTuanUtil.concatParams(map);
			String json = HttpClientUtil.sendGet(url, param);
			HashMap<String, Object> data_ = (HashMap<String, Object>) JSONParser
					.parse(json, new HashMap<String, Object>().getClass());
			data = (String) data_.get("data");
		} catch (Exception e) {
			System.out.println(e);
		}
		return data;
	}

	@Override
	@SuppressWarnings("unchecked")
	public String sendArrivedToMt(Long orderId) {
		
		Integer timestamp = (int) (System.currentTimeMillis() / 1000);
		String data = null;
		
		Channel channel = channelMapper.findKeyById(orderId);
		
		try {
			Map<String, String> map = new HashMap<String, String>();
			map.put("order_id", orderId.toString());
			String url = "http://test.waimaiopen.meituan.com/api/v1/order/arrived";
			String md5 = MeiTuanUtil.signRequest(url, map, channel.getAppKey(), channel.getAppSecret(),
					timestamp);
			map.put("app_id", channel.getAppKey());
			map.put("timestamp", timestamp.toString());
			map.put("sig", md5);
			String param = MeiTuanUtil.concatParams(map);
			String json = HttpClientUtil.sendGet(url, param);
			HashMap<String, Object> data_ = (HashMap<String, Object>) JSONParser
					.parse(json, new HashMap<String, Object>().getClass());
			data = (String) data_.get("data");
		} catch (Exception e) {
			System.out.println(e);
		}
		return data;
	}

	@Override
	@SuppressWarnings("unchecked")
	public String sendAgreeRefundToMt(Long orderId) {
		
		Integer timestamp = (int) (System.currentTimeMillis() / 1000);
		String data = null;
		
		Channel channel = channelMapper.findKeyById(orderId);
		
		try {
			Map<String, String> map = new HashMap<String, String>();
			map.put("order_id", orderId.toString());
			map.put("reason", "同意用户的退款申请");
			String url = "http://test.waimaiopen.meituan.com/api/v1/order/refund/agree";
			String md5 = MeiTuanUtil.signRequest(url, map, channel.getAppKey(), channel.getAppSecret(),
					timestamp);
			map.put("app_id", channel.getAppKey());
			map.put("timestamp", timestamp.toString());
			map.put("sig", md5);
			String param = MeiTuanUtil.concatParams(map);
			String json = HttpClientUtil.sendGet(url, param);
			HashMap<String, Object> data_ = (HashMap<String, Object>) JSONParser
					.parse(json, new HashMap<String, Object>().getClass());
			data = (String) data_.get("data");
		} catch (Exception e) {
			System.out.println(e);
		}
		return data;
	}

}
